<!--
 * @作者: kerwin
 * @公众号: 大前端私房菜
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>聊天室</h1>
    <input type="text" id="text"><button id="send">send</button>

    <select id="select">

    </select>
    <!-- 建立socket连接 带着token，后端验证 -->
    <script>
        var select = document.querySelector("#select")
        var send = document.querySelector("#send")
        var text = document.querySelector("#text")
        const WebSocketType = {
            Error: 0, //错误
            GroupList: 1,
            GroupChat: 2,
            SingleChat: 3
        }
        const ws = new WebSocket(`ws://localhost:8080?token=${localStorage.getItem("token")}`)
        ws.onopen = () => {
            console.log("open")

        }
        ws.onmessage = (msgObj) => {
            // console.log(msgObj.data)
            msgObj = JSON.parse(msgObj.data)

            switch (msgObj.type) {
                case WebSocketType.Error:
                    localStorage.removeItem("token")
                    location.href = "/login"
                    break;
                case WebSocketType.GroupList:
                    console.log(JSON.parse(msgObj.data))
                    const onlineList = JSON.parse(msgObj.data)
                    select.innerHTML = ""
                    select.innerHTML = `<option value="all">all</option>` + onlineList.map(item => `
                        <option value="${item.username}">${item.username}</option>
                    `).join("")
                    break;
                case WebSocketType.GroupChat:
                    var title = msgObj.user ? msgObj.user.username : "广播"
                    console.log(title + " : " + msgObj.data)
                    break;

                case WebSocketType.SingleChat:
                    
                    console.log(msgObj.user.username + " : " + msgObj.data)
                    break;
            }
        }


        send.onclick = () => {
            if (select.value === "all") {
                // console.log("群发")
                ws.send(createMessage(WebSocketType.GroupChat, text.value))
            } else {
                // console.log("siliao")
                ws.send(createMessage(WebSocketType.SingleChat, text.value, select.value))
            }
        }

        function createMessage(type, data, to) {
            return JSON.stringify({
                type,
                data,
                to
            })
        }
    </script>
</body>

</html>